package com.work.cos.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.work.cos.domain.entity.UserEntity;
import com.work.cos.domain.vo.ComServiceResVo;
import com.work.cos.domain.vo.ComUserToken;
import com.work.cos.mapper.base.IUserMapper;
import com.work.cos.service.interfc.IUserService;
import com.work.cos.service.interfc.IVerCodeLogService;
import com.work.cos.util.CodeUtils;
import com.work.cos.util.ConfigInfo;
import com.work.cos.util.StringEncrypt;
import com.work.cos.util.ThirdPullUtil;
import com.work.cos.util.page.PageInfo;

/**
 * Created by intel on 2018/3/30.
 */

@Service
public class UserServiceImpl implements IUserService {

    /**
     * Logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    
    private static final long GLOBAL_SESSION_TIMEOUT = 1000 * 60 * 60 * 24;  // 1000毫秒*60*60*24 = 24小时

    @Resource
    private IUserMapper userMapper;
    
	@Autowired
	private IVerCodeLogService verCodeLogService;

    @Override
    public PageInfo<UserEntity> findAllUsers(UserEntity userInfo) {
        return null;
    }

    @Override
    public PageInfo<UserEntity> findUsersPage(UserEntity userInfo) {
        return null;
    }

    @Override
    public UserEntity findUsers(Long phone, String password) {
        return userMapper.findUsers(phone, password);
    }

    @Override
    public List<UserEntity> findUserDyn(Map<String, Object> map) {
        return null;
    }

    @Override
    public int countDyn(Map<String, Object> map) {
        return 0;
    }

    @Override
    public boolean addUsers(UserEntity entity) {
        return userMapper.save(entity) > 0;
    }

    @Override
    public boolean addUsersAndAccount(UserEntity userInfo) {
        return false;
    }

    @Override
    public boolean saveUserAndCoupon(UserEntity userInfo, String couponCode) {
        return false;
    }

    @Override
    public boolean updateUsers(UserEntity userInfo) {
        return false;
    }

    @Override
    public boolean checkUsers(String phoneNum, String password, String registerCode, String token) {
        return false;
    }

    @Override
    public int getCountByMobile(Long phone) {
        return 0;
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public boolean UserImage(Long userId, String newPath) {
        return false;
    }

    @Override
    public boolean updateUserPwd(Long phone, String password) {
        return false;
    }

    @Override
    public boolean updateAvator(Long userId, String avatorName) {
        return false;
    }

    @Override
    public UserEntity findUsersByUserId(Long userId) {
        return null;
    }

    @Override
    public boolean getMemberMobileIsExist(Long phone) {
        return userMapper.getMemberMobileIsExist(phone) == 1;
    }

	@Override
	@Transactional
	public ComServiceResVo doRegister(Long phone, String password, String verCode, Long relationCode) {
		
		UserEntity entity = this.findUsers(phone, "");
		
		if(null != entity){
			
			LOGGER.info("mobile controller: register user is exits ...");
			return ComServiceResVo.returnErrorMessage("用户已经注册!");
		}
		
		String msg = "";
		String verCodeDb = verCodeLogService.getVerCodeNow(phone);
		
		// 验证码是否正确
		if (!verCode.equals(verCodeDb)) {
			
			msg = "验证码不正确!";
			LOGGER.info("mobile controller: register error...", msg);
			return ComServiceResVo.returnErrorMessage(msg);
		}
		
		
		if (!verCode.equals(verCodeDb)) {
			msg = "该用户已经注册!";
			LOGGER.info("mobile controller: register error...", msg);
			return ComServiceResVo.returnErrorMessage(msg);
		}
		
		UserEntity userInfo = new UserEntity();
		userInfo.setNickName(CodeUtils.getNickName(ConfigInfo.NCIK_FIX));
		userInfo.setPassword(StringEncrypt.Encrypt(password, ""));
		userInfo.setPhone(phone);
		userInfo.setCredits(Long.parseLong("0"));
		userInfo.setShareCode(System.currentTimeMillis());
		if(null != relationCode){
			userInfo.setRelationCode(relationCode);
		}
		if (verCode.equals(verCodeDb)) {
			
			boolean flag = this.addUsers(userInfo);
			
			if(flag){
				
				UserEntity entityNew = this.findUsers
						(phone, StringEncrypt.Encrypt(password, ""));
				
				ThirdPullUtil.sendRegisterInfo(entityNew.getId().toString(), password);
				
				return ComServiceResVo.returnSuccessStatus();
			}
			
			return ComServiceResVo.returnErrorMessage("注册失败!");
		
		} else{
			
			return ComServiceResVo.returnErrorMessage("验证码不正确!");
		}
	}

	@Override
	public ComServiceResVo doLogin(Long phone, String password, HttpServletRequest request) {
		
		boolean flag = this.getMemberMobileIsExist(phone);
		
		if(flag){	
			//此处手机端传输为明文传输
			UserEntity userInfo = this.findUsers(phone, StringEncrypt.Encrypt(password, ""));
			
			if (null != userInfo) {
				
				LOGGER.info("mobile controller: login success...");
				return ComServiceResVo.returnEntity(userInfo);
				
			}else{
				
				UserEntity checkInfo = this.findUsers(phone, "");
				
				if(null != checkInfo && StringUtils.isEmpty(checkInfo.getPassword())){
					
					ComUserToken token = new ComUserToken(phone.toString(), 
							checkInfo.getPassword() , 1 , false, false);
					Subject subject = SecurityUtils.getSubject();
		            subject.login(token);
		            subject.getSession().setTimeout(GLOBAL_SESSION_TIMEOUT);// session time out , default=30min
		            request.getSession().setAttribute("userId", checkInfo.getId());
		            request.getSession().setAttribute("phone", checkInfo.getPhone());
					LOGGER.debug("mobile controller: login success...");
					
					return ComServiceResVo.returnEntity(checkInfo);
				}else{
					
					LOGGER.info("login controller: login error...message={}", "密码不正确!");
					return ComServiceResVo.returnErrorMessage("密码不正确!");
				}
			}
		}else{
			
			LOGGER.info("login controller: login error...message={}", "请先注册!");
			return ComServiceResVo.returnErrorMessage("请先注册!");
		}
	}
}
